package cn.iocoder.yudao.module.mqtt.util;

import cn.hutool.http.HttpUtil;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.mqtt.controller.admin.littree.vo.LisToken;
import cn.iocoder.yudao.module.mqtt.controller.admin.littree.vo.site.*;
import cn.iocoder.yudao.module.mqtt.controller.admin.littree.vo.site.page.LisPagesRes;
import cn.iocoder.yudao.module.mqtt.controller.admin.littree.vo.site.res.LisListRes;
import cn.iocoder.yudao.module.mqtt.controller.admin.littree.vo.site.res.LisRes;
import cn.iocoder.yudao.module.mqtt.dal.dataobject.device.DeviceDO;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.esotericsoftware.minlog.Log;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.HashMap;
import java.util.Map;

public class LisTreeUtil {


    public static String tokenUrl = "http://cs.litreesmart.com/xcloud-auth/oauth/token";

    //站点数量和设备总数、离线数量、报警数量
    public static String countUrl = "http://cs.litreesmart.com/xcloud-lisheng/api.litree/v1/sites/resource_offline_count";
    public static String sitesUrl = "http://cs.litreesmart.com/xcloud-lisheng/admin.lisheng/v1/sites";//3.站点列表


    public static String listUrl = "http://cs.litreesmart.com/xcloud-flex-hda/api.hda/v2/hda/list"; //10.获取网关历史数据
    public static String waterUrl = "http://cs.litreesmart.com/xcloud-flex-hda/api.hda/v2/hda/water";//6.获取站点的日、月、年、总产水量
    /**
     * 获取token
     * @return
     */
    public static LisToken getToken() {
        // 设置请求参数
        Map<String, Object> params = new HashMap<>();
        params.put("username", "xcsl");
        params.put("password", "Xcsl#123456");
        params.put("grant_type", "password");
        // 将Map转换为JSON字符串
        JSONObject jsonParams = new JSONObject(params);
        String jsonStr = jsonParams.toString();
        Map<String, Object> map = HttpSysUtil.postToken(tokenUrl, jsonStr);
        if ("00000".equals(map.get("code"))) {
            LisToken tokenLis = JSONObject.parseObject(map.get("data").toString(), LisToken.class);
            return tokenLis;
        }
        return null;
    }

    public static  LisRes<LisSiteCountVO>  getCount(String url, String access_token) {
        Map<String, String> header = new HashMap<>();
        header.put("Authorization", "bearer " + access_token);
        String result = HttpSysUtil.doGet(url, null, header);
        // 正确写法：使用 TypeReference 指定泛型类型
        LisRes<LisSiteCountVO> res = JSONObject.parseObject(  result, new TypeReference<LisRes<LisSiteCountVO>>() {} );
        return res;
    }


    /**
     * 3.站点列表
     * @param url
     * @param access_token
     * @return
     */
    public static LisPagesRes<LisSiteContentVO> getSites(String url, String access_token, Integer page, Integer size) {
        Map<String, Object> params = new HashMap<>();
        params.put("conditions", "FRONTPAGE");
        params.put("page", page);
        params.put("size", size);
        Map<String, String> header = new HashMap<>();
        header.put("Authorization", "bearer " + access_token);

        System.out.println("请求参数：" + JSONObject.toJSONString( params));
        String result = HttpUtil.createGet(sitesUrl).addHeaders(header).form(params).execute().body();
        LisPagesRes<LisSiteContentVO> res = JSONObject.parseObject(  result, new TypeReference< LisPagesRes<LisSiteContentVO>>() {} );
        return res;
    }

    /**
     * 6.获取站点的日、月、年、总产水量
     * @param access_token
     * @param getewayId
     * @return
     */
    public static LisListRes<LisShunVO> getWater(String access_token, String getewayId) {
        Map<String, Object> params = new HashMap<>();
        params.put("database", "hda");
        params.put("tableName", getewayId);
        Map<String, String> header = new HashMap<>();
        header.put("Authorization", "bearer " + access_token);
        String result = HttpUtil.createGet(waterUrl).addHeaders(header).form(params).execute().body();
//        LisListRes res = JSONObject.parseObject(result, LisListRes.class);
        LisListRes<LisShunVO> res = JSONObject.parseObject(result, new TypeReference< LisListRes<LisShunVO>>() {} );
        return res;
    }

    public static LisRes<LisListVO> getListMin10(String getewayId,String access_token) {
        // 获取当前时间
        LocalDateTime currentTime = LocalDateTime.now();
        LocalDateTime tenMinutesAgo = currentTime.minusMinutes(59);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String beginDate = tenMinutesAgo.format(formatter);
        String endDate = currentTime.format(formatter);

        Map<String, Object> params = new HashMap<>();
        params.put("tableName", getewayId );
        params.put("pageNumber", 1);
        params.put("pageSize", 20);
        params.put("devicePoints", "产水累积量,产水流量");
        params.put("beginDate", beginDate);
        params.put("endDate", endDate);

        Map<String, String> header = new HashMap<>();
        header.put("Authorization", "bearer " + access_token);
        System.out.println("请求参数：" + JSONObject.toJSONString( params));
        String result = HttpUtil.createGet(listUrl).addHeaders(header).form(params).execute().body();
        LisRes<LisListVO> res = JSONObject.parseObject(result, new TypeReference<LisRes<LisListVO>>() {} );
        return res;
    }

    public static LisRes<LisListVO> getListLastHour( String beginDate ,  String endDate, String access_token,String getewayId) {
        Map<String, Object> params = new HashMap<>();
        params.put("tableName", getewayId );
        params.put("pageNumber", 1);
        params.put("pageSize", 20);
        params.put("devicePoints", "产水累积量,产水流量");
        params.put("beginDate", beginDate);
        params.put("endDate", endDate);
        params.put("timeUnit", "hour"); //消失

        Map<String, String> header = new HashMap<>();
        header.put("Authorization", "bearer " + access_token);
        System.out.println("请求参数：" + JSONObject.toJSONString( params));
        String result = HttpUtil.createGet(listUrl).addHeaders(header).form(params).execute().body();
        System.out.println("响应结果：" + result);
        LisRes<LisListVO> res = JSONObject.parseObject(result, new TypeReference<LisRes<LisListVO>>() {} );
        return res;
    }


    /**
     * 计算总页数
     * @param totalCount 总数量（需要分页的总数）
     * @param pageSize 每页大小（每页显示的数量）
     * @return 总页数（当总数量为0时返回0，当每页大小不合法时返回0）
     */
    public static int calculateTotalPages(int totalCount, int pageSize) {
        // 边界处理：总数量为0时，总页数为0
        if (totalCount <= 0) {
            return 0;
        }
        // 边界处理：每页大小必须大于0，否则返回0（避免除数为0）
        if (pageSize <= 0) {
            return 0;
        }
        // 计算逻辑：总数除以每页大小，有余数则加1页
        return (totalCount + pageSize - 1) / pageSize;
    }

    public static void main(String[] args) {
        LisToken lis = getToken();
        // 输出结果
        String beginDate = LisTreeUtil.getDayBegin();
        String endDate = LisTreeUtil.getLastHourEnd();
        System.out.println("开始时间：" + beginDate + "  结束时间：" + endDate);


        LisListRes<LisShunVO> water = getWater(lis.getAccess_token(), "300224010733");

        System.out.println(water);
        //
         //请求参数：{"beginDate":"2025-08-22 00:00:00","pageNumber":1,"endDate":"2025-08-22 19:59:59","pageSize":20,
        // "devicePoints":"产水累积量,产水流量","tableName":"300223121790","timeUnit":"hour"}
        //响应结果：{"code":"00000","data":{"pageSize":20,"pageNumber":1,"list":[],"count":0},"msg":"SUCCESS"}
        LisRes<LisListVO> resVO =  getListLastHour(beginDate,endDate,lis.getAccess_token(),"300223080695");
        LisListVO data = resVO.getData();
        for (int j = 0; j < data.getList().size(); j++) {
            System.out.println();
            System.out.println( data.getList().get(j).getTime() + "-------------------" + data.getList().get(j).get产水累积量() + " - "  + data.getList().get(j).get产水流量());
        }
//        LisRes<LisSiteCountVO> res = getCount(countUrl, lis.getAccess_token());
//        Log.info("获取设备总数: ---  " + res.getData());
//        Integer deviceCount = Integer.parseInt(res.getData().getDeviceCount());
//        Integer countTotalPages = calculateTotalPages(deviceCount, 100);
//        Log.info("计算发送多少次接口: ---  " + res.getData());
//        Integer count = 0;
//        for (int i = 0; i < countTotalPages; i++) {
//            LisPagesRes<LisSiteContentVO> sites = getSites(sitesUrl, lis.getAccess_token(), i, 100);
//            for (int j = 0; j < sites.getData().getContent().size(); j++) {
//                count++;
////                System.out.println(count+ " -- " +  sites.getData().getContent().get(j).getSiteName());
//                LisSiteContentVO lisSiteVO = sites.getData().getContent().get(j);
//                System.out.println("--------->>>>>>>>>>>"+lisSiteVO.getSiteName());
////                DeviceDO deviceDO = new DeviceDO();
////                BeanUtils.copyProperties(lisSiteVO,deviceDO);
////                System.out.println("----"+deviceDO);
//            }
//        }
    }















    public static LocalDateTime convertToUtcLocalDateTime(String isoUtcString) {
        if (isInvalidInput(isoUtcString)) {
            return null;
        }

        try {
            // 优先使用OffsetDateTime解析（更适合处理UTC偏移量）
            OffsetDateTime offsetDateTime = OffsetDateTime.parse(isoUtcString);
            return offsetDateTime.toLocalDateTime();
        } catch (DateTimeParseException e) {
            try {
                // 备选方案：使用ZonedDateTime解析
                ZonedDateTime zonedDateTime = ZonedDateTime.parse(isoUtcString);
                return zonedDateTime.toLocalDateTime();
            } catch (DateTimeParseException ex) {
                return null;
            }
        }
    }

    /**
     *
     * @return
     */
    public static  String getLastHourBegin(){
        // 获取当前时间
        LocalDateTime currentTime = LocalDateTime.now();
        // 计算上个小时的基准时间（当前时间减1小时）
        LocalDateTime lastHour = currentTime.minusHours(1);
        // 上个小时的开始时间（如：08:00:00）
        LocalDateTime lastHourStart = lastHour
                .withMinute(0)   // 分钟设为0
                .withSecond(0)   // 秒设为0
                .withNano(0);    // 纳秒设为0
        // 格式化输出
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String beginDate = lastHourStart.format(formatter);
        return beginDate;
    }

    public static  String getLastHourEnd(){
        // 获取当前时间
        LocalDateTime currentTime = LocalDateTime.now();
        // 计算上个小时的基准时间（当前时间减1小时）
        LocalDateTime lastHour = currentTime.minusHours(1);
        // 上个小时的结束时间（如：08:59:59.999999999）
        LocalDateTime lastHourEnd = lastHour
                .withMinute(59)  // 分钟设为59
                .withSecond(59)  // 秒设为59
                .withNano(999_999_999);  // 纳秒设为最大值

        // 格式化输出
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String endDate = lastHourEnd.format(formatter);
        return endDate;
    }
    public static  String getDayBegin(){
        // 获取当天0点的LocalDateTime对象
        LocalDateTime midnight = LocalDate.now(ZoneId.systemDefault()).atStartOfDay();
        // 定义输出格式（例如：yyyy-MM-dd HH:mm:ss）
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 转换为字符串
        String midnightStr = midnight.format(formatter);
        return midnightStr;
    }
    /**
     * 检查输入字符串是否有效
     */
    private static boolean isInvalidInput(String input) {
        return input == null || input.trim().isEmpty();
    }
}
